import utils from "@/utils/utils.js";
import apis from "@/api/index.js";//全局API
import { getToken, setToken, removeToken } from '@/utils/auth'
import axios from 'axios'

const useCounter = defineStore('counter', {
  state: () => {
    return {
      depts: [],
      orderStatus: [
        { name: "全部", value: "" },
        { name: "待付款", value: "wait" },
        { name: "待拣货", value: "success" },
        { name: "待配送", value: "delivery" },
        { name: "退款中", value: "refund" },
        { name: "已退款", value: "refunded" },
        { name: "已取消", value: "cancel" },
        { name: "已完成", value: "finish" },
      ],
      permissionHasLoaing: false,//路由是否已加载
      ycAdminParams: {},//亚城后台参数
      pageHeight: 0,
      classCardHeight: 0,
      dictOptions: {},//报名所属列表
      classTabs: [
        { name: "排课信息", value: 1 },
        { name: "班级学员", value: 2 },
        { name: "签到情况", value: 3 },
        { name: "考试管理", value: 8 },
        { name: "班级管理手册", value: 4 },
        { name: "教务管理手册", value: 5 },
        { name: "班级相册", value: 6 },
        { name: "收款凭证", value: 7 },
      ],
      courseList: [],//课程列表
    }
  },
  getters: {
    //部门树
    depsTree: (state) => {
      return utils.transformArray([...state.depts], "_id", "parentId")
    },
    updateUser() {
      return this.ycAdminParams.userInfo.userInfo.userName
    },
    accountUser() {
      return this.ycAdminParams.userInfo.userInfo
    },
    isLocalhost: (state) => {
      let location = window.location
      if (location.hostname && (location.hostname == "localhost")) return true
      return false
    },
    isAdmin: (state) => {
      let account = state.ycAdminParams.userInfo.userInfo.account
      return account == "admin"
    },
  },
  actions: {
    //班级管理-是否展示操作按钮
    isShowActionBtn(info) {
      if (this.isAdmin) return true
      //如果已结业
      if (info.status == 2) return false
      //判断是不是本班级老师
      return info.classTeacherId == this.accountUser._id
    },
    async downLoadTemplate(type, filename) {
      let url = await apis.fileTemplate({
        data: { type },
        type: "downLoad",
      });
      if (!filename) return window.location.href = url
      try {
        // 使用 fetch 获取 Excel 文件
        const response = await fetch(url);
        // 确保响应是有效的
        if (!response.ok) { throw new Error('Network response was not ok'); }
        // 获取文件数据
        const blob = await response.blob();
        // 创建一个指向该 Blob 对象的 URL
        const urlBlob = URL.createObjectURL(blob);
        // 创建一个临时的 <a> 元素
        const a = document.createElement('a');
        a.href = urlBlob;
        a.download = filename; // 设置自定义文件名
        // 将 <a> 元素添加到 DOM
        document.body.appendChild(a);
        // 模拟点击 <a> 元素，触发下载
        a.click();
        // 移除 <a> 元素
        document.body.removeChild(a);
        // 释放 Blob URL
        URL.revokeObjectURL(urlBlob);
      } catch (error) {
        console.error('Error downloading the file:', error);
      }
    },

    //导入模板上传
    async importTemplate(files, type) {
      let obj = {
        name: "",
        path: "",
        type,
      };
      obj.name = files[0].name;
      obj.path = await this.uploadFile(files[0]);
      await apis.fileTemplate({
        data: obj,
        type: "update",
      });
      utils.showToast("上传成功");
    },
    init() {
      let ycAdminParams: any = localStorage.getItem("ycAdminParams")
      if (!ycAdminParams) ycAdminParams = {}
      if (utils.isJSON(ycAdminParams)) ycAdminParams = JSON.parse(ycAdminParams);
      this.ycAdminParams = utils.deepcopy(ycAdminParams)
      if (ycAdminParams.token) this.getUserInfo()
      this.allCourse()
    },
    status_format(e) {
      for (let index = 0; index < this.orderStatus.length; index++) {
        const element = this.orderStatus[index];
        if (element.value == e) return element.name
      }
    },
    //登录
    async login(obj) {
      let resp = await apis.login(obj);
      setToken(resp.token)
      this.token = resp.token
    },
    //自动登录
    autoLogin(token) {
      setToken(token)
      this.token = token
    },
    //用户用户信息
    async getUserInfo(account) {
      let params
      let ycAdminParams: any = localStorage.getItem("ycAdminParams");
      if (utils.isJSON(ycAdminParams)) ycAdminParams = JSON.parse(ycAdminParams);
      if (ycAdminParams && ycAdminParams.hasOwnProperty("userInfo")) {
        let { userInfo } = ycAdminParams.userInfo
        params = userInfo.account
      } else {
        params = account
      }
      let resp = await apis.userInfo({ account: params })
      let newRouter = this.convertToVueRoutes(resp.menusTree);
      this.setYcParams("userInfo", resp)
      this.setYcParams("newRouter", newRouter)
    },

    setYcParams(type, params) {
      let ycAdminParams: any = localStorage.getItem("ycAdminParams")
      if (!ycAdminParams) ycAdminParams = {}
      if (utils.isJSON(ycAdminParams)) ycAdminParams = JSON.parse(ycAdminParams);
      ycAdminParams[type] = params;
      localStorage.setItem("ycAdminParams", JSON.stringify(ycAdminParams));
      this.ycAdminParams = { ...ycAdminParams };
    },

    //设置element路由
    convertToVueRoutes(data) {
      const routes = [];
      data.forEach((item) => {
        const route = {
          path: item.path,
          name: item.path,
          component: item.parentId == 0 ? "Layout" : item.component,
          meta: {
            title: item.menuName,
            icon: item.icon ? item.icon : "#",
            link: null,
            noCache: false,
          },
        };
        route["hidden"] = item.visible == 1 ? false : true;
        //一级目录
        if (item.parentId == 0) {
          route["alwaysShow"] = true;
          route["path"] = item.path.includes("/") ? item.path : `/${item.path}`;
          route["redirect"] = "noRedirect";
        }
        if (item.children && item.children.length > 0) {
          route["children"] = this.convertToVueRoutes(item.children);
        }
        routes.push(route);
      });
      return routes;
    },

    //上传文件
    async uploadFile(file) {
      //定义FormData对象 存储文件
      let mf = new FormData();
      //将图片文件放入mf
      mf.append("file", file);
      let resp = await apis.uploadFile(mf)
      return resp
    },

    async uploadFileSeenLove(file) {
      let base64 = await utils.imageToBase64(file)
      let resp = await apis.uploadFileSeenLove({
        file_name: file.name,
        filedata: base64
      })
      return `https://oss.seenlove.com/${resp}`
    },

    tagBgColor(e) {
      switch (e) {
        case 0:
          return "#FAD5C1";
          break;
        case 1:
          return "#FCF9D7";
          break;
        case 2:
          return "#ECF7E8";
          break;
        case 3:
          return "#F7E7F7";
          break;
        case 4:
          return "#E5BCBE";
          break;
        case 6:
          return "#E5BCBE";
          break;
        case 7:
          return "#E0F3FB";
          break;
        case 10:
          return "#ECF7E8";
          break;
        default:
          break;
      }
    },

    tagColor(e) {
      switch (e) {
        case 0:
          return "#D07743";
          break;
        case 1:
          return "#F5C73C";
          break;
        case 2:
          return "#35965F";
          break;
        case 3:
          return "#663786";
          break;
        case 4:
          return "#A51C1B";
          break;
        case 6:
          return "#A51C1B";
          break;
        case 7:
          return "#216592";
          break;
        case 10:
          return "#35965F";
          break;
        default:
          break;
      }
    },

    //获得七牛信息
    async getQIniuInfo() {
      let resp = await axios.post(`https://app.taozapp.cn/api/uploadFile/uploadPhoto`)
      return resp.data
    },

    //七牛上传
    async qiniuUpload(file) {
      let qiNiu = await this.getQIniuInfo()

      //定义FormData对象 存储文件
      let mf = new FormData()
      //将图片文件放入mf
      mf.append('file', file)
      mf.append('token', qiNiu.token)
      return new Promise((resolve, reject) => {
        axios({
          url: 'https://upload-z2.qiniup.com',
          method: 'post',
          data: mf,
        })
          .then(data => {
            //let img = counter.qiNiu.cdnUrl + data.data.key
            let img = 'https://qn.taozapp.cn/' + data.data.key
            resolve(img)
          })
          .catch(function (err) {
            console.log("七牛上传失败", err)
          })
      })
    },

    //教务绑定
    async getArchiveBinding(classId) {
      return await apis.classData({
        type: "relatedArchives",
        data: { classId },
      });
    },

    //课程安排表
    async courseRankingTable(classId) {
      let isQuantityMatching = false
      let resp = await apis.classReport({
        type: "B1-list",
        data: { classId },
      });
      let archiveBinding = await this.getArchiveBinding(classId)
      //如果有绑定教案
      if (archiveBinding.length) {
        let ret = await apis.scheduleRelevant({
          type: "archives-curriculum-list",
          data: { archivesId: archiveBinding[0]._id },
        });
        isQuantityMatching = (ret.length == resp.length)
        for (let index = 0; index < resp.length; index++) {
          const element = resp[index];
          if (index <= ret.length - 1) {
            element.newDate = utils.dateTimeFormateFn(element.date, "monthDate")
            element.timeRange = ret[index].timeRange; //时段
            element.curriculum = ret[index].curriculum; //课程
            element.lecturerName = archiveBinding[0].lecturerName;
          }
        }
      }
      return { tableData: resp, isQuantityMatching }
    },

    //课程安排表导出参数
    async courseCreateExportParams(e) {
      let array = utils.deepcopy(e);
      let data = <any>[];
      array.forEach((element, index) => {
        data.push({
          newDate: utils.dateTimeFormateFn(element.courseDate, "monthDate"),
          classIndex: index + 1,
          timeRange: element.timeRange
            ? element.timeRange
            : element.classStartTime + "~" + element.classEndTime,
          classHours: 2,
          curriculum: element.curriculum,
          lecturerName: element.lecturerName,
        });
      });
      return data;
    },

    //学院信息列表
    async studentInfo(classId) {
      return await apis.classReport({
        type: "B3-list",
        data: { classId },
      });
    },

    //学员信息导出参数
    studentExportParams(e) {
      let tableData = utils.deepcopy(e);
      let list = <any>[];
      for (let index = 0; index < tableData.length; index++) {
        const element = tableData[index];
        let obj = {
          index: (index + 1).toString(),
          name: element.baseInfo.name,
          sex: this.getGenderByIdCard(element.baseInfo.identityCard),
          mobile: element.baseInfo.mobile,
          address: element.address || "",
          remark: element.remark || "",
        };
        list.push(obj);
      }
      return list;
    },

    //身份证解析性别
    getGenderByIdCard(idCard) {
      if (!idCard || idCard.length !== 18) {
        throw new Error("Invalid ID card number");
      }
      const sexCode = idCard.charAt(16);
      const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
      return gender;
    },

    //授课计划
    async getTeachingPlan(classId) {
      let archiveBindingList = []
      let resp = await apis.classReport({
        type: "B1-list",
        data: { classId },
      });
      let archiveBinding = await this.getArchiveBinding(classId)
      console.log("archiveBinding", archiveBinding)
      if (archiveBinding.length) {
        archiveBindingList = await apis.scheduleRelevant({
          type: "archives-curriculum-list",
          data: { archivesId: archiveBinding[0]._id },
        });
      }
      return { tableData: resp, archiveBindingList }
    },

    //教学日记
    async getTeachingJournal(classId) {
      let archiveBindingList = []
      let archiveBinding = await this.getArchiveBinding(classId)
      if (archiveBinding.length) {
        archiveBindingList = await apis.scheduleRelevant({
          type: "archives-curriculum-journal-list",
          data: { archivesId: archiveBinding[0]._id },
        });
      }
      return { archiveBindingList }
    },

    //授课计划导出参数
    async teachingPlanExportParams(e, archiveBindingList, classId) {
      let that = this;
      let array = utils.deepcopy(e);
      let data = <any>[];
      let llTotal = 0;
      let sxTotal = 0;
      let model = await getB7Details()
      array.forEach((element, index) => {
        let theoreticalClassHours = field_format(index, "theoreticalClassHours");
        let practicalTrainingHours = field_format(index, "practicalTrainingHours");
        data.push({
          date: utils.dateTimeFormateFn(element.date, "monthDate"),
          classIndex: field_format(index, "classIndex"),
          timeRange: field_format(index, "timeRange"),
          classHour: field_format(index, "classHour"),
          curriculum: field_format(index, "curriculum"),
          llHour: theoreticalClassHours,
          sxHour: practicalTrainingHours,
        });
        if (theoreticalClassHours) llTotal += theoreticalClassHours * 1;
        if (practicalTrainingHours) sxTotal += practicalTrainingHours * 1;
      });
      return { list: data, llTotal, sxTotal, ...model };

      function field_format(index, field) {
        if (!archiveBindingList.length) return;
        if (index <= archiveBindingList.length - 1) return archiveBindingList[index][field];
        return ""
      }

      async function getB7Details() {
        let model = {
          requirement: "",
          aKey: "",
          difficulty: "",
          afterword: "",
        }
        let resp = await apis.classReport({
          type: "B7-details",
          data: { classId },
        });
        let archiveBinding = await that.getArchiveBinding(classId)
        console.log("archiveBinding", archiveBinding)
        if (resp) {
          model = utils.formatFunction(resp, { ...model });
        } else if (archiveBinding && archiveBinding.length) {
          let res = await apis.scheduleRelevant({
            type: "archives-teaching-details",
            data: { archivesId: archiveBinding[0]._id },
          });
          if (res) {
            model.requirement = res.instructionalObjective;
            model.aKey = res.teachingFocus;
            model.difficulty = res.teachingDifficulties;
            model.afterword = res.executionAfterword;
          }
        }
        for (let key in model) {
          model[key] = model[key].split("\n");
        }
        return model
      }
    },

    //获取班级信息
    async getClassInfo(classId) {
      return await apis.classData({
        type: "details",
        data: { _id: classId },
      });
    },

    //教案信息导出参数
    async lessonPlanExportParams(e, archiveBindingList, classId) {
      let classDetails = await this.getClassInfo(classId)
      let array = utils.deepcopy(e);
      let data = <any>[];
      for (let index = 0; index < array.length; index++) {
        let element = array[index];
        let theoreticalClassHours = field_format(index, "theoreticalClassHours");
        let practicalTrainingHours = field_format(index, "practicalTrainingHours");
        let courseType = <any>[]
        if (theoreticalClassHours && (theoreticalClassHours * 1)) courseType.push("理论课");
        if (practicalTrainingHours && (practicalTrainingHours * 1)) courseType.push("实训课");
        let obj = {
          date: `${element.date} ${field_format(index, "timeRange")}`,
          occupationalLevel: `${classDetails.occupational}(${classDetails.level})` || "",
          className: classDetails.className,
          curriculum: field_format(index, "curriculum"),
          instructionalObjective: field_format(index, "instructionalObjective"),
          trainingContent: field_format(index, "trainingContent"),
          trainingEquipment: field_format(index, "trainingEquipment"),
          teachingFocus: field_format(index, "teachingFocus"),
          teachingDifficulties: field_format(index, "teachingDifficulties"),
          teachingAids: field_format(index, "teachingAids"),
          teachingPostscript: field_format(index, "teachingPostscript"),
          courseType: courseType.join("、"),
          classIndex: field_format(index, "classIndex"),
        };
        data.push(obj);
      }
      function field_format(index, key) {
        if (!archiveBindingList.length) return;
        if (index <= archiveBindingList.length - 1) return archiveBindingList[index][key];
        return ""
      }
      return data;
    },

    //教案附表的导出
    async lessonPlanAppendixExportParams(classId) {
      let archiveBinding = await this.getArchiveBinding(classId)
      let tableData = <any>[]
      if (archiveBinding.length) {
        tableData = await apis.scheduleRelevant({
          type: "archives-appendix-list",
          data: { archivesId: archiveBinding[0]._id },
        });
      }
      tableData.forEach((element) => {
        element.contentCourses = element.contentCourses.split("\n");
      });
      return tableData;
    },

    //教学日志的导出
    async teachingLogExportParams(e, list, classId) {
      let array = utils.deepcopy(e);
      let classData = await this.getClassInfo(classId)
      let data = <any>[];
      array.forEach((element, index) => {
        data.push({
          date: element.date,
          classIndex: field_name(index, "classIndex"),
          timeRange: field_name(index, "timeRange"),
          classHours: field_name(index, "classHour"),
          curriculum: field_name(index, "curriculum"),
          teachingNewsNotes: field_name(index, "teachingNewsNotes"),
          lecturerName: classData.assessedTeacher || classData.teachingTeacher,
        });
      });
      let arr = <any>[];
      let list2 = utils.splitArray(data, 2);
      list2.forEach((element, index) => {
        arr.push({ page: index + 1, child: element, classId: classData.classId || "" });
      });
      return arr;

      function field_name(index, key) {
        if (!list.length) return;
        if (index <= list.length - 1) return list[index][key];
        return ""
      }
    },

    //学员评议表列表
    async collegeEvaluationExportParams(classId) {
      let classDetail = await this.getClassInfo(classId)
      let { tableData } = await this.courseRankingTable(classId)
      console.log("tableData11", tableData)

      let array = await apis.classReport({
        type: "student-evaluate-class",
        data: { classId },
      });
      console.log("评议表", array)
      let data = <any>[];
      let suggestionsOpinions = <any>[]  //意见建议
      array.forEach((element, index) => {
        if (element.suggestionsOpinions) {
          suggestionsOpinions.push(element.suggestionsOpinions)
        }

        data.push({
          //序号
          index: index + 1,
          //态度
          attitude1: element.teachingAttitude == "好",
          attitude2: element.teachingAttitude == "较好",
          attitude3: element.teachingAttitude == "尚可",
          attitude4: element.teachingAttitude == "差",
          //内容
          content1: element.contentCourses == "好",
          content2: element.contentCourses == "较好",
          content3: element.contentCourses == "尚可",
          content4: element.contentCourses == "差",
          //方法
          method1: element.trainingMethods == "好",
          method2: element.trainingMethods == "较好",
          method3: element.trainingMethods == "尚可",
          method4: element.trainingMethods == "差",
          //手段
          device1: element.teachingDevices == "好",
          device2: element.teachingDevices == "较好",
          device3: element.teachingDevices == "尚可",
          device4: element.teachingDevices == "差",
          //讲解
          demo1: element.explainDemo == "好",
          demo2: element.explainDemo == "较好",
          demo3: element.explainDemo == "尚可",
          demo4: element.explainDemo == "差",
          //巡回
          guidance1: element.guidanceAspect == "好",
          guidance2: element.guidanceAspect == "较好",
          guidance3: element.guidanceAspect == "尚可",
          guidance4: element.guidanceAspect == "差",
          //课时
          hour1: element.completionStatus == "好",
          hour2: element.completionStatus == "较好",
          hour3: element.completionStatus == "尚可",
          hour4: element.completionStatus == "差",
          suggestionsOpinions: element.suggestionsOpinions ? element.suggestionsOpinions : "",
          //评议时间
          year: utils.dateTimeFormateFn(element["fillTime"], "year"),
          month: utils.dateTimeFormateFn(element["fillTime"], "month"),
          day: utils.dateTimeFormateFn(element["fillTime"], "day"),
          //等级
          occupationalLevel: `${classDetail.occupational}(${classDetail.level})`,
          teachingTeacher: classDetail.teachingTeacher,
          className: classDetail.className,
          classHours: format_name(element.lessonScheduleId, 'unitClassHours'),
          //评议的课程
          curriculumName: format_name(element.lessonScheduleId, 'curriculum'),
          //授课教师
          lecturerName: format_name(element.lessonScheduleId, 'lecturerName'),
        });
      });
      return { suggestionsOpinions: suggestionsOpinions.toString(), data };

      function format_name(id, type) {
        for (let index = 0; index < tableData.length; index++) {
          const element = tableData[index];
          if (element._id == id) return element[type];
        }
      }
    },

    //培训结果统计
    async trainingResultExportParams(classId) {
      let attendanceRequired = 0; //应出勤人数
      let toClassStudent = 0; //到课人数
      let numberAppraisers = 0; //鉴定人数
      let certifiedIndividuals = 0; //获证人数
      let numberRegistrations = 0; //注册人数

      //全部排课
      let arr = await apis.teachingScheduleData({ type: "query", data: { classId }, });
      //班级学员
      let rows = await apis.classStudent({ type: "query", data: { classId } });
      let students = utils.deepcopy(rows);
      // console.log("排课", arr)
      // console.log("学员", students)
      arr.forEach((item) => {
        students.forEach((element) => {
          if (element.userState == 1) {
            attendanceRequired++
          } else {
            //停课日期时间戳
            let suspensionClassDate = utils.getTimeFn(
              element.suspensionClassDate
            );
            let date = utils.getTimeFn(element.date);
            if (date < suspensionClassDate) {
              attendanceRequired++
            }
          }
        });
      });
      students.forEach((element) => {
        if (element.declarationBatchNumber) numberRegistrations++
        if (element.isExamination && element.isExamination == 1) {
          certifiedIndividuals++
        }
        if (element.isExamination == 2) {
        } else {
          numberAppraisers++
        }
      });
      //console.log("numberRegistrations", numberRegistrations)
      //有多少人到课了
      let resp = await apis.classNameCalling({
        type: "query",
        data: { classId, status: 1 },
      });
      toClassStudent = resp.length;
      //console.log("计算出勤率", toClassStudent, attendanceRequired)
      return {
        numberAppraisers, //鉴定人数
        numberRegistrations, //注册人数
        attendance:
          toClassStudent == 0
            ? 0
            : ((toClassStudent / attendanceRequired) * 100).toFixed(2), //出勤率
        certifiedNum: certifiedIndividuals, //获证人数
        quaRate: quaRate(), //培训合格率
        qualificationRate: ((certifiedIndividuals / numberAppraisers) * 100).toFixed(2), //鉴定合格率
      }

      function quaRate() {
        if (certifiedIndividuals == 0 || numberRegistrations == 0) return 0;
        return ((certifiedIndividuals / numberRegistrations) * 100).toFixed(2);
      }
    },

    //B6学员花名册
    async studentRosterExportParams(classId) {
      let classInfo = await this.getClassInfo(classId)

      let resp = await apis.classStudent({
        type: "list",
        data: { classId, pageIndex: 1, pageSize: 150, }
      });
      let arr = <any>[]
      resp.rows.forEach((element, index) => {
        arr.push({
          index: index + 1,
          declarationBatchNumber: element.declarationBatchNumber || "",
          name: field_format(element, 'name'),
          identityCard: field_format(element, 'identityCard'),
          education: field_format(element, 'education'),
          school: field_format(element, 'school') || "",
          graduationMajor: field_format(element, 'graduationMajor'),
          workYears: field_format(element, 'workYears'),
        })
      });
      return { list: arr, level: classInfo.level, occupational: classInfo.occupational }


      function field_format(item, key) {
        let row = item.source ? item.user_data : item.user_Info.baseInfo;
        return row[key];
      }
    },

    //展示企业
    showEnterprise(row, key) {
      //console.log("嘻嘻", row, key)
      let employed_Status = row.employed_Status
      //如果没有设置过是否就业
      if (!employed_Status) enterprise_format(row, key)
      if (employed_Status && employed_Status.includes("未")) return "-"
      return enterprise_format(row, key)

      function enterprise_format(row, key) {
        if (key == "enterprise") {
          if (row[key]) return row[key]
          if (row["enterprise_department"]) return row["enterprise_department"]
          return "-"
        } else {
          return row[key] || ""
        }
      }
    },

    //接口调用时间间隔
    apiTime(key, differ = 1000) {
      let now = Date.now()
      let apiTime = this.qcParams.apiTime || []
      let index = this.$utils.findIndexByField(apiTime, "key", key)
      if (index != -1) {
        let oldTime = apiTime[index].time
        if (now - oldTime < differ) {
          apiTime[index].time = now
          this.setRelease("apiTime", apiTime)
          return false
        }
        apiTime[index].time = now
      } else {
        apiTime.push({ key, time: now })
      }
      this.setRelease("apiTime", apiTime)
      return true
    },

    //导出附件
    async exportAttachment(data) {
      let resp
      if (utils.isJsonArray(data) == "jsonArr") {
        resp = utils.deepcopy(data)
      } else {
        resp = await apis.orderAction({ type: "getOrderByOutTradeNo", data });
      }
      let attachments = [];
      let list = utils.deepcopy(resp);
      list.forEach((item) => {
        let { model, relationList } = item.approvalContent;
        let obj = {
          arr: <any>[],
          fileName: `${item.approvalContent.model.name}-${item.approvalContent.model.identityCard}-附件`,
        };
        let modelArr = [
          {
            name: "身份证",
            value: "identification_scancopy",
          },
          {
            name: "毕业证书",
            value: "certificate_scancopy",
          },
        ];
        modelArr.forEach((element) => {
          if (model.hasOwnProperty(element.value)) {
            let news = [];
            if (utils.isString(model[element.value])) {
              news = model[element.value].split(",");
            } else if (utils.isJsonArray(model[element.value])) {
              news = model[element.value];
            }
            news.forEach((item, index) => {
              obj.arr.push({
                path: item["path"] ? item["path"] : item,
                name: element.name + index + "_" + model.name,
              });
            });
          }
        });

        if (relationList && relationList.length) {
          relationList.forEach((element) => {
            let files = []
            if (utils.isString(element.value)) {
              files = element.value.split(",");
            } else {
              files = element.value;
            }
            files.forEach((xx, current2) => {
              obj.arr.push({
                path: xx.path ? xx.path : xx,
                name: fileName(element.title) + current2 + "_" + model.name,
              });
            });
          });
          attachments.push(obj);
        }
      });
      //return console.log("attachments", attachments);

      if (!attachments.length) return utils.showToast("没有需要下载的文件", 0);
      attachments.forEach((element) => {
        utils.JSZipDownLoad(element.arr, element.fileName);
      });

      function fileName(str) {
        let a = getBracketContents(str);
        if (a.length) return a[0];
        return str;
      }

      //获取书名号里面的值
      function getBracketContents(str) {
        // 正则表达式匹配书名号内的内容
        const regex = /《([^>]+)》/g;
        let match;
        let results = [];
        // 循环查找所有匹配项
        while ((match = regex.exec(str)) !== null) {
          results.push(match[1]); // 添加书名号内的内容到结果数组
        }
        return results; // 返回包含所有内容的数组
      }
    },

    //全部课程
    async allCourse() {
      this.courseList = await apis.course({ type: "query", data: { allData: 1 } });
      console.log("全部课程", this.courseList)
    },

    //报名所属列表
    async getAffiliation(key = 'registration_affiliation') {
      if (this.dictOptions[key]) return
      let { rows } = await apis.dict({
        type: "list",
        data: { code: key },
      });
      this.dictOptions[key] = rows[0].data;
    }
  }
})

export default useCounter